package com.aerozhonghuan.oknet2;

import android.text.TextUtils;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by zhangyunfei on 17/7/12.
 */

public class HttpGetUtil {

    /**
     * build 请求
     * @param url
     * @param callback1
     * @return
     */
    public static OkNetCall get(String url, final CommonCallback<String> callback1) {
        if (TextUtils.isEmpty(url)) throw new NullPointerException("url is null");
        Request request = new Request.Builder().url(url).build();

        Call call = OknetHttpUtil.newCall(request);
        call.enqueue(new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {
                if (callback1 != null)
                    callback1.onFailure(0, e, null, null);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                int httpCode = response.code();
                if (response.isSuccessful()) {
                    String bodyString = response.body().string();
                    if (callback1 != null) callback1.onSuccess(bodyString, null, bodyString);
                } else {
                    String bodyString = response.body().string();
                    if (callback1 != null)
                        callback1.onFailure(httpCode, new Exception("未期望的返回" + httpCode), null, bodyString);
                }
            }
        });

        return new OkNetCall(call);
    }

}
